// miniprogram/pages/counter_detail/counter_detail.js
const db = require('../../utils/db');
const datetime = require('../../utils/datetime');

let id;

Page({
  data: {
    id: {
      type: String,
      value: ''
    },
    busy: {
      type: Boolean,
      value: true
    },
    record: {
      type: Object,
      value: {}
    },
    found: {
      type: Boolean,
      value: false
    },
    late: {
      type: Boolean,
      value: false
    },
    allowPickup: {
      type: Boolean,
      value: false
    }
  },

  onLoad: function (options) {
    id = options.id;
  },

  onReady: function () {
    this.setData({
      id: id || '',
      busy: true
    });
    db.getRecord(id).then(entry => {
      if (entry != null) {
        const isLate = Date.now() > entry['expectedReturnTime'];
        entry['borrowTime'] = datetime.toFriendlyTime(entry['borrowTime']);
        entry['expectedReturnTime'] = datetime.toFriendlyTime(entry['expectedReturnTime']);
        if (entry['returnTime']) {
          entry['returnTime'] = datetime.toFriendlyTime(entry['returnTime']);
        }
        db.listDeliveries().then(deliveries => {
          const ids = deliveries.map(it => it.id);
          this.setData({
            found: true,
            busy: false,
            record: entry,
            late: isLate,
            allowPickup: ids.indexOf(id) < 0
          });
        });
      } else {
        this.setData({
          found: false,
          busy: false
        });
      }
    }).catch(e => console.log(e));
  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onTitleTap: function () {
    wx.navigateTo({
      url: '../book_details/book_details?mode=id&input=' + this.data.record.book[0]._id,
    });
  },

  onProxyReturnTap: function () {
    wx.navigateTo({
      url: '../proxy_return/proxy_return?recordId=' + this.data.record._id,
    });
  },

  onProxyBorrowTap: function () {
    wx.navigateTo({
      url: '../proxy_borrow/proxy_borrow?id=' + this.data.record.book[0]._id,
    });
  }
})